package client

import (
	"sync"

	"github.com/redis/go-redis/v9"
)

const (
	defaultPoolSize   = 256
	defaultMaxRetries = 3
)

var (
	redisClientInstance     *RedisClient
	redisClientInstanceOnce sync.Once
)

type RedisClient struct {
	client redis.UniversalClient
}

type RedisClientOptions struct {
	PoolSize   int
	MaxRetries int
}

func NewRedisClient(addr []string, password string, opt ...RedisClientOptions) *RedisClient {
	poolSize := defaultPoolSize
	maxRetries := defaultMaxRetries
	if len(opt) > 0 {
		poolSize = opt[0].PoolSize
		maxRetries = opt[0].MaxRetries
	}

	// 使用 UniversalOptions 来配置，支持单机、集群和哨兵
	opts := &redis.UniversalOptions{
		Addrs:      addr,
		Password:   password,
		DB:         0,
		PoolSize:   poolSize,
		MaxRetries: maxRetries,
	}

	return &RedisClient{
		client: redis.NewUniversalClient(opts),
	}
}

// GetRedisClient 对外提供获取RedisClient的
func GetRedisClient() *RedisClient {
	initRedisClient()
	return redisClientInstance
}

func initRedisClient() {
	redisClientInstanceOnce.Do(func() {
		redisClientInstance = NewRedisClient([]string{"127.0.0.1:6379"}, "", RedisClientOptions{})
	})
}
